package person.tavion.transaction.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 两个消费组进行消费Topic，测试是否会有重复消费
 * 得出结果：
 * Topic 与 消费组 的关系，就像是聊天室，topic是发布消息A，其他消费组都能收到消息A，消息是一对多，每次增加一组，就会从0offset开始读取Topic
 *
 */
@Service
public class UserTestConsumerService {
    @KafkaListener(topics = {"myTestUser"},groupId = "myUserGroup", containerFactory="kafkaListenerContainerFactory")
//    public void kafkaListener(String message){
    // 批量消费
    public void kafkaListener(List<ConsumerRecord<String, String>> recordList){
        System.out.println("消费列表："+recordList.size());
        for (ConsumerRecord<String, String> consumerRecord : recordList) {
            kafkaListener(consumerRecord);
        }

    }
    // 单次消费
    public void kafkaListener(ConsumerRecord<String, String> record){
        String key = record.key().toString();
        String value = record.value().toString();
        System.out.println(record.offset()+" \t "+key+" \t "+ value);
        System.out.println("消费完成"+value);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    @KafkaListener(topics = {"myTestUser"},groupId = "myUserTestGroup", containerFactory="kafkaListenerContainerFactory")
//    public void kafkaListener(String message){
    // 批量消费
    public void kafkaListener2(List<ConsumerRecord<String, String>> recordList){
        System.out.println("消费列表："+recordList.size());
        for (ConsumerRecord<String, String> consumerRecord : recordList) {
            kafkaListener(consumerRecord);
        }

    }

}
